package com.acwing.partition21;

import java.io.*;
import java.util.Deque;
import java.util.LinkedList;

/**
 * @author `RKC`
 * @date 2022/1/4 20:09
 */
public class AC2060奶牛选美bfs {

    private static final int N = 51, M = 51;
    private static char[][] graph = new char[N][M];
    private static boolean[][] visited = new boolean[N][N];
    private static int n = 0, m = 0;
    private static final int[][] dirs = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] s = reader.readLine().split("\\s+");
        n = Integer.parseInt(s[0]);
        m = Integer.parseInt(s[1]);
        for (int i = 0; i < n; i++) {
            String str = reader.readLine();
            for (int j = 0; j < m; j++) {
                graph[i][j] = str.charAt(j);
            }
        }
        writer.write(bfs() + "\n");
        writer.flush();
    }

    private static int bfs() {
        //双端队列
        Deque<int[]> deque = new LinkedList<>();
        boolean flag = false;
        for (int i = 0; i < n; i++) {
            if (flag) break;
            for (int j = 0; j < m; j++) {
                if (graph[i][j] == 'X') {
                    deque.addLast(new int[]{i, j, 0});
                    flag = true;
                    break;
                }
            }
        }
        while (!deque.isEmpty()) {
            int[] curr = deque.pollFirst();
            int x = curr[0], y = curr[1], step = curr[2];
            if (graph[x][y] == 'X' && step > 0) return step;
//            if (graph[x][y] == 'X') System.out.printf("(%d,%d) step=%d\n", x, y, step);
            if (visited[x][y]) continue;
            visited[x][y] = true;
            //遍历当前点的周围点
            for (int[] dir : dirs) {
                int x1 = x + dir[0], y1 = y + dir[1];
                if (x1 < 0 || x1 >= n || y1 < 0 || y1 >= m || visited[x1][y1]) continue;
                if (graph[x1][y1] == 'X') deque.addFirst(new int[]{x1, y1, step});
                else deque.addLast(new int[]{x1, y1, step + 1});
            }
        }
        return 0;
    }
}
